import { useState, useEffect, useCallback } from 'react'
import './index.scss'
import NavBar from '../../extract/index'
import { useNavigate } from 'react-router-dom'
import { useUser } from '../../hooks/useUser'

function Fbbyq() {
  const navigate = useNavigate()
  const { isLoggedIn, token, userInfo } = useUser()
  const [formData, setFormData] = useState({
    title: '',
    department: '',
    mainSymptom: '',
    symptomDetails: '',
    hospitalName: '',
    startTime: '',
    endTime: '',
    treatmentProcess: ''
  })
  const [errors, setErrors] = useState<{ [key: string]: boolean }>({})
  const [showDepartmentDropdown, setShowDepartmentDropdown] = useState(false)
  const [showMainSymptomDropdown, setShowMainSymptomDropdown] = useState(false)
  
  // 日期选择器状态
  const [showDatePicker, setShowDatePicker] = useState(false)
  const [datePickerType, setDatePickerType] = useState<'start' | 'end'>('start')
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear())
  const [selectedMonth, setSelectedMonth] = useState(new Date().getMonth() + 1)
  const [selectedDay, setSelectedDay] = useState(new Date().getDate())
  
  // 提示信息状态
  const [showValidationMessage, setShowValidationMessage] = useState(false)
  const [validationMessage, setValidationMessage] = useState('')
  
  // API数据状态
  const [departmentOptions, setDepartmentOptions] = useState<{id: number, name: string}[]>([])
  const [symptomData, setSymptomData] = useState<{id: number, name: string}[]>([])
  
  // 发布状态
  const [isSubmitting, setIsSubmitting] = useState(false)

  // 备用病症数据（与API返回的科室名称保持一致）
  const fallbackSymptomData = {
    '内科': ['发热', '咳嗽', '胸闷', '乏力', '头痛', '腹痛', '恶心', '呕吐'],
    '骨科': ['关节疼痛', '腰背疼痛', '骨折', '肌肉酸痛', '运动损伤', '关节痛', '颈椎痛', '腰椎痛'],
    '眼科': ['视力模糊', '眼痛', '眼干', '流泪', '眼红', '飞蚊症', '近视', '远视'],
    '小儿科': ['发热', '咳嗽', '腹泻', '呕吐', '皮疹', '哭闹', '食欲不振', '发育迟缓'],
    '急诊科': ['胸痛', '呼吸困难', '意识不清', '外伤', '中毒', '高热', '急性腹痛', '休克'],
    '皮肤性病': ['皮疹', '瘙痒', '脱发', '皮肤干燥', '痤疮', '湿疹', '皮炎', '过敏'],
    '耳鼻喉科': ['听力下降', '耳鸣', '鼻塞', '流鼻涕', '喉咙痛', '声音嘶哑', '打鼾', '眩晕'],
    '精神病科': ['失眠', '焦虑', '抑郁', '情绪不稳', '记忆力下降', '注意力不集中', '幻觉', '妄想']
  }

  // 根据选择的科室获取对应的病症选项
  const getSymptomOptions = () => {
    // 优先使用API数据
    if (symptomData.length > 0) {
      return symptomData.map(item => item.name)
    }
    
    // 如果API数据为空，使用备用数据
    return fallbackSymptomData[formData.department as keyof typeof fallbackSymptomData] || []
  }

  // 获取科室数据
  const fetchDepartmentData = useCallback(async () => {
    try {
      // 由于外部API无法访问，直接使用备用数据
      setDepartmentOptions(getFallbackDepartments())
    } catch (error) {
      console.error('获取科室数据失败:', error)
      setDepartmentOptions(getFallbackDepartments())
    }
  }, [])

  // 获取备用科室数据
  const getFallbackDepartments = () => [
    { id: 1, name: '内科' },
    { id: 2, name: '骨科' },
    { id: 3, name: '眼科' },
    { id: 4, name: '小儿科' },
    { id: 5, name: '急诊科' },
    { id: 6, name: '皮肤性病' },
    { id: 7, name: '耳鼻喉科' },
    { id: 8, name: '精神病科' }
  ]

  // 获取病症数据
  const fetchSymptomData = async (departmentId: number) => {
    try {
      // 由于外部API无法访问，使用备用数据
      console.log('使用备用病症数据，科室ID:', departmentId)
      
      // 根据科室ID获取对应的病症数据
      const departmentName = departmentOptions.find(dept => dept.id === departmentId)?.name
      if (departmentName && fallbackSymptomData[departmentName as keyof typeof fallbackSymptomData]) {
        const symptoms = fallbackSymptomData[departmentName as keyof typeof fallbackSymptomData]
        const symptomData = symptoms.map((symptom, index) => ({
          id: index + 1,
          name: symptom
        }))
        setSymptomData(symptomData)
      } else {
        setSymptomData([])
      }
    } catch (error) {
      console.error('获取病症数据失败:', error)
      setSymptomData([])
    }
  }

  // 组件加载时获取科室数据
  useEffect(() => {
    fetchDepartmentData()
  }, [fetchDepartmentData])

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
    // 清除错误状态
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: false
      }))
    }
  }

  const handleSelectOption = (field: string, value: string, departmentId?: number) => {
    handleInputChange(field, value)
    
    // 关闭对应的下拉框
    if (field === 'department') {
      setShowDepartmentDropdown(false)
      // 选择科室后清空病症选择
      setFormData(prev => ({
        ...prev,
        mainSymptom: ''
      }))
      // 清空之前的病症数据
      setSymptomData([])
      // 立即打开病症下拉框
      setShowMainSymptomDropdown(true)
      // 异步获取新科室的病症数据
      if (departmentId) {
        fetchSymptomData(departmentId)
      }
    }
    if (field === 'mainSymptom') setShowMainSymptomDropdown(false)
  }

  // 打开日期选择器
  const openDatePicker = (type: 'start' | 'end') => {
    setDatePickerType(type)
    setShowDatePicker(true)
  }

  // 确认日期选择
  const confirmDateSelection = () => {
    const dateString = `${selectedYear}.${selectedMonth.toString().padStart(2, '0')}.${selectedDay.toString().padStart(2, '0')}`
    const field = datePickerType === 'start' ? 'startTime' : 'endTime'
    handleInputChange(field, dateString)
    setShowDatePicker(false)
  }

  // 生成年份选项
  const generateYears = () => {
    const currentYear = new Date().getFullYear()
    const years = []
    for (let i = currentYear - 10; i <= currentYear + 5; i++) {
      years.push(i)
    }
    return years
  }

  // 生成月份选项
  const generateMonths = () => {
    return Array.from({ length: 12 }, (_, i) => i + 1)
  }

  // 生成日期选项
  const generateDays = () => {
    const daysInMonth = new Date(selectedYear, selectedMonth, 0).getDate()
    return Array.from({ length: daysInMonth }, (_, i) => i + 1)
  }

  const handleSubmit = async () => {
    // 检查登录状态
    if (!isLoggedIn) {
      setValidationMessage('请先登录后再发布')
      setShowValidationMessage(true)
      setTimeout(() => {
        setShowValidationMessage(false)
      }, 3000)
      return
    }

    // 验证必填字段（带蓝标的字段）
    const requiredFields = [
      { field: 'title', label: '标题' },
      { field: 'department', label: '就诊科室' },
      { field: 'mainSymptom', label: '主要病症' },
      { field: 'symptomDetails', label: '病症详情' }
    ]

    const missingFields = requiredFields.filter(item => !formData[item.field as keyof typeof formData])

    if (missingFields.length > 0) {
      // 设置错误状态
      const newErrors: { [key: string]: boolean } = {}
      missingFields.forEach(item => {
        newErrors[item.field] = true
      })
      setErrors(newErrors)
      
      // 显示校验提示
      const missingLabels = missingFields.map(item => item.label).join('、')
      setValidationMessage(`请填写以下必填项：${missingLabels}`)
      setShowValidationMessage(true)
      
      // 3秒后自动隐藏提示
      setTimeout(() => {
        setShowValidationMessage(false)
      }, 3000)
      return
    }

    // 开始提交
    setIsSubmitting(true)
    
    try {
      // 获取科室ID
      const selectedDepartment = departmentOptions.find(dept => dept.name === formData.department)
      const departmentId = selectedDepartment?.id || 1
      
      // 构建提交数据
      const submitData = {
        title: formData.title,
        departmentId: departmentId,
        mainSymptom: formData.mainSymptom,
        detail: formData.symptomDetails,
        hospitalName: formData.hospitalName || '',
        startTime: formData.startTime || '',
        endTime: formData.endTime || '',
        treatmentProcess: formData.treatmentProcess || ''
      }
      
      console.log('提交数据:', submitData)
      console.log('API URL:', '/user/sickCircle/v1/addSickCircle')
      console.log('用户登录状态:', isLoggedIn)
      console.log('用户Token:', token)
      console.log('用户信息:', userInfo)
      console.log('localStorage token:', localStorage.getItem('token'))
      console.log('localStorage userId:', localStorage.getItem('userId'))
      console.log('localStorage sessionId:', localStorage.getItem('sessionId'))
      
      // 由于API接口不存在，我们使用模拟发布功能
      // 在实际项目中，这里应该调用真实的后端API
      console.log('模拟发布数据:', submitData)
      
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟发布成功
      console.log('模拟发布成功')
      
      // 将新发布的帖子保存到localStorage，这样byq页面就能显示
      const newPost = {
        sickCircleId: Date.now(), // 使用时间戳作为唯一ID
        title: submitData.title,
        releaseTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
        detail: submitData.detail,
        collectionNum: 0,
        commentNum: 0,
        departmentId: submitData.departmentId,
        mainSymptom: submitData.mainSymptom,
        hospitalName: submitData.hospitalName,
        startTime: submitData.startTime,
        endTime: submitData.endTime,
        treatmentProcess: submitData.treatmentProcess
      }
      
      // 获取现有的帖子列表
      const existingPosts = JSON.parse(localStorage.getItem('publishedPosts') || '[]')
      // 将新帖子添加到列表开头
      existingPosts.unshift(newPost)
      // 保存到localStorage
      localStorage.setItem('publishedPosts', JSON.stringify(existingPosts))
      
      setValidationMessage('发布成功！')
      setShowValidationMessage(true)
      
      // 2秒后跳转到byq页面
      setTimeout(() => {
        setShowValidationMessage(false)
        navigate('/byq', { state: { from: 'fbbyq' } })
      }, 2000)
    } catch (error: unknown) {
      console.error('发布出错:', error)
      const err = error as { response?: { data?: { message?: string }, status?: number } }
      console.error('错误详情:', err.response?.data)
      console.error('错误状态:', err.response?.status)
      
      let errorMessage = '网络错误，请检查网络连接'
      if (err.response?.data?.message) {
        errorMessage = err.response.data.message
      } else if (err.response?.status === 401) {
        errorMessage = '请先登录'
      } else if (err.response?.status === 403) {
        errorMessage = '没有权限发布'
      } else if (err.response?.status && err.response.status >= 500) {
        errorMessage = '服务器错误，请稍后重试'
      }
      
      setValidationMessage(errorMessage)
      setShowValidationMessage(true)
      setTimeout(() => {
        setShowValidationMessage(false)
      }, 3000)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className='fbbyq'>
    <div>
        <NavBar />
      </div>

      {/* 表单内容 */}
      <div className='fbbyq-form'>
        {/* 病症详情 */}
        <div className='form-section'>
          <div className='form-item'>
            <div className='input-container'>
              <span className='input-asterisk'>*</span>
              <input
                type="text"
                className={`form-input ${errors.title ? 'error' : ''}`}
                placeholder='请输入标题(最多20个字)'
                value={formData.title}
                onChange={(e) => handleInputChange('title', e.target.value)}
                maxLength={20}
              />
            </div>
          </div>

          <div className='form-item'>
            <div className='input-container'>
              <span className='input-asterisk'>*</span>
              <div className={`form-select ${errors.department ? 'error' : ''} ${showDepartmentDropdown ? 'open' : ''}`} onClick={() => setShowDepartmentDropdown(!showDepartmentDropdown)}>
                <span className='select-text'>{formData.department || '请选择就诊科室'}</span>
                <div className='select-arrow'>▼</div>
              </div>
              {showDepartmentDropdown && (
                <div className='dropdown-menu'>
                  <div className='dropdown-grid'>
                    {departmentOptions.map((option, index) => (
                      <div key={index} className='dropdown-grid-item' onClick={() => handleSelectOption('department', option.name, option.id)}>
                        {option.name}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>

          <div className='form-item'>
            <div className='input-container'>
              <span className='input-asterisk'>*</span>
              <div className={`form-select ${errors.mainSymptom ? 'error' : ''} ${showMainSymptomDropdown ? 'open' : ''}`} onClick={() => setShowMainSymptomDropdown(!showMainSymptomDropdown)}>
                <span className='select-text'>{formData.mainSymptom || '请选择主要病症'}</span>
                <div className='select-arrow'>▼</div>
              </div>
              {showMainSymptomDropdown && (
                <div className='dropdown-menu'>
                  <div className='dropdown-grid'>
                    {!formData.department ? (
                      <div className='dropdown-grid-item' style={{gridColumn: '1 / -1', color: '#999'}}>
                        请先选择就诊科室
                      </div>
                    ) : (
                      getSymptomOptions().map((option, index) => (
                        <div key={index} className='dropdown-grid-item' onClick={() => handleSelectOption('mainSymptom', option)}>
                          {option}
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>

          <div className='form-item'>
            <div className='textarea-container'>
              <span className='textarea-asterisk'>*</span>
              <textarea
                className={`form-textarea ${errors.symptomDetails ? 'error' : ''}`}
                placeholder='请输入病症详情'
                value={formData.symptomDetails}
                onChange={(e) => handleInputChange('symptomDetails', e.target.value)}
                maxLength={300}
              />
              <span className='char-limit'>不超过300字</span>
            </div>
          </div>
        </div>

        {/* 最近一段治疗经历 */}
        <div className='treatment-section'>
          <span className='section-title'>请输入最近一段治疗经历</span>

          <div className='treatment-form'>
            <div className='form-item'>
              <input
                type="text"
                className='form-input'
                placeholder='请输入医院名称'
                value={formData.hospitalName}
                onChange={(e) => handleInputChange('hospitalName', e.target.value)}
              />
            </div>

          <div className='form-item'>
            <div className='form-select' onClick={() => openDatePicker('start')}>
              <span className='select-text'>{formData.startTime || '请选择开始时间'}</span>
              <div className='select-arrow'>▼</div>
            </div>
          </div>

          <div className='form-item'>
            <div className='form-select' onClick={() => openDatePicker('end')}>
              <span className='select-text'>{formData.endTime || '请选择结束时间'}</span>
              <div className='select-arrow'>▼</div>
            </div>
          </div>

            <div className='form-item'>
              <textarea
                className='form-textarea'
                placeholder='请输入治疗过程'
                value={formData.treatmentProcess}
                onChange={(e) => handleInputChange('treatmentProcess', e.target.value)}
              />
            </div>
          </div>
        </div>
          
          {/* 图片上传区域 */}
          <div className='image-upload-section'>
            <div className='upload-instruction'>
              最多可添加6张图片，长按为图片排序
            </div>
            <div className='image-upload-area'>
              <div className='image-placeholder'>
                <span className='plus-icon'>+</span>
              </div>
            </div>
          </div>

          {/* 悬赏额度 */}
          <div className='bounty-section'>
            <div className='bounty-toggle'>
              <span className='bounty-label'>提升悬赏额度</span>
              <div className='toggle-switch'>
                <div className='toggle-handle'></div>
              </div>
            </div>
          </div>

          {/* 发表按钮 */}
          <div className='submit-section'>
            <div className='bounty-description'>
              提升额度可获得更多的关注，得到更多建议
            </div>
            <button 
              className='submit-btn' 
              onClick={handleSubmit}
              disabled={isSubmitting}
            >
              {isSubmitting ? '发布中...' : '发表'}
            </button>
          </div>
      </div>

      {/* 日期选择器 */}
      {showDatePicker && (
        <div className='date-picker-overlay'>
          <div className='date-picker-modal'>
            <div className='date-picker-header'>
              <h3 className='date-picker-title'>选择日期</h3>
              <button className='date-picker-close' onClick={() => setShowDatePicker(false)}>×</button>
            </div>
            
            <div className='date-picker-info'>
              {datePickerType === 'start' ? '开始时间' : '结束时间'} {selectedYear}.{selectedMonth.toString().padStart(2, '0')}.{selectedDay.toString().padStart(2, '0')}
            </div>
            
            <div className='date-picker-wheels'>
              <div className='date-wheel'>
                {generateYears().map((year) => (
                  <div 
                    key={year} 
                    className={`date-wheel-item ${year === selectedYear ? 'selected' : ''}`}
                    onClick={() => setSelectedYear(year)}
                  >
                    {year}年
                  </div>
                ))}
              </div>
              
              <div className='date-wheel'>
                {generateMonths().map((month) => (
                  <div 
                    key={month} 
                    className={`date-wheel-item ${month === selectedMonth ? 'selected' : ''}`}
                    onClick={() => setSelectedMonth(month)}
                  >
                    {month}月
                  </div>
                ))}
              </div>
              
              <div className='date-wheel'>
                {generateDays().map((day) => (
                  <div 
                    key={day} 
                    className={`date-wheel-item ${day === selectedDay ? 'selected' : ''}`}
                    onClick={() => setSelectedDay(day)}
                  >
                    {day}日
                  </div>
                ))}
              </div>
            </div>
            
            <button className='date-picker-confirm' onClick={confirmDateSelection}>
              确定
            </button>
          </div>
        </div>
      )}

      {/* 校验提示 */}
      {showValidationMessage && (
        <div className='validation-message'>
          <div className={`validation-content ${validationMessage.includes('成功') ? 'success' : ''}`}>
            <span className={`validation-text ${validationMessage.includes('成功') ? 'success' : ''}`}>{validationMessage}</span>
            <button className='validation-close' onClick={() => setShowValidationMessage(false)}>×</button>
          </div>
        </div>
      )}
    </div>
  )
}

export default Fbbyq